<template>
  <div class="login_container">
    <div class="login_box">
<!--      logo区域-->
      <div class="logo">
        <img src="./../assets/logo.png" alt="">
      </div>
<!--      表单登录区域-->
      <el-form class="login_form" :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input  prefix-icon="iconfont icon-users" v-model="loginForm.username"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input  prefix-icon="iconfont icon-3702mima" v-model="loginForm.password" type="password"/>
        </el-form-item>
        <el-form-item class="login">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      // 登录表单的数据绑定
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 登录变淡规则验证
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
  },
  methods: {
    // 表单重置功能实现
    reset () {
      this.$refs.loginFormRef.resetFields()
    },
    // 表单登录校验
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        // 如果校验不通过 直接return
        if (!valid) return
        console.log(valid)
        // eslint-disable-next-line no-unused-vars
        const { data: res } = await this.$http.post('login', this.loginForm)
        // eslint-disable-next-line no-undef
        if (res.meta.status !== 200) return this.$message.error('您输入的用户名或密码不正确')
        this.$message.success('登录成功')
        // 当后台校验成功之后把token存储在sessionStroage中
        window.sessionStorage.setItem('token', res.data.token)
        // 通过编程式导航跳转到主页
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.login_container
  position: relative
  background-color #2b4b6b
  width: 100%
  height: 100%
  .login_box
    position: absolute;
    top: 50%
    left: 50%
    transform translate(-50%, -50%)
    width: 400px
    height: 300px
    background-color: #ffffff
    border-radius 3px
    .logo
      position: absolute;
      top: 0
      left: 50%
      transform translate(-50%, -50%)
      width: 100px
      height: 100px
      background-color: #ccc
      border-radius 50%
      padding: 5px
      img
        width: 100%
        height: 100%
        border-radius 50%
    .login_form
      position: absolute;
      top 80px
      left 0
      padding: 0 20px
      width: 100%
      .login
        text-align: right
</style>
